<template>
  <div class="login-container">
    <!-- 标题 -->
    <van-nav-bar title="kxs-登录">
      <template #left>
        <img class="logo" src="../../assets/img/logo.png" />
      </template>
    </van-nav-bar>
      <!-- 表单 -->
    <van-form @submit="onSubmitFn">
      <van-field
        v-model="formLogin.mobile"
        required
        label="手机号"
        placeholder="输入手机号"
        :rules="rules.tel"
      />
      <van-field
        v-model="formLogin.code"
        type="password"
        required
        label="验证码"
        placeholder="输入验证码"
        :rules="rules.pwd"
      />
      <div style="margin: 16px">
        <van-button
          :loading='isLoading'
          :disabled ='isLoading'
          loading-text="拼命加载中..."
          color="#f00"
          round
          block
          type="info"
          native-type="submit"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
// import { loginAPI } from '@/api'
import { Notify } from 'vant'
// import { mapState, mapMutations } from 'vuex'
import { mapActions } from 'vuex'
export default {
  name: 'Login',
  data () {
    return {
      // ******************************************手机号和验证码
      formLogin: {
        mobile: '13888888888',
        code: '246810'
      },
      // ******************************************校验规则
      rules: {
        tel: [
          { required: true, message: '请填写手机号', trigger: 'onChange' },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '请输入正确手机号',
            trigger: 'onChange'
          }
        ],
        pwd: [
          { required: true, message: '请填写验证码', trigger: 'onChange' },
          {
            pattern: /^\d{6}$/,
            message: '请输入正确验证码',
            trigger: 'onChange'
          }
        ]
      },
      // ******************************************控制加载，禁用状态
      isLoading: false
    }
  },
  methods: {
    // ...mapState(['token', 'refreshToken']),
    // ...mapMutations(['setToken', 'setRefreshToken']),
    ...mapActions(['asyncLogin']),
    async onSubmitFn () {
      this.isLoading = true
      try {
        await this.asyncLogin(this.formLogin)// 变同步

        // const res = await loginAPI(this.formLogin)
        // console.log(res)

        // const { token, refreshToken } = res.data.data
        // this.setToken(token)
        // this.setRefreshToken(refreshToken)

        // this.isLoading = false//放到finally
        // 成功通知
        Notify({ type: 'success', message: '登陆成功' })
        this.$router.push({
          // path: '/layout'
          path: this.$route.query.qu || 'layout'
        })
      } catch (err) {
        console.error(err)
        // 危险通知
        Notify({ type: 'danger', message: '请输入正确的手机号和验证码' })
      } finally {
        this.isLoading = false// 获得数据后恢复,放在这里就不管它是成功或者失败都会恢复正常
      }
    }
  }
}
</script>

<style lang="less" scoped>
.logo {
  width: 100px;
  height: 30px;
}
</style>
